<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="企业全称" prop="companyName">
        <el-input
            v-model="queryParams.companyName"
            placeholder="请输入企业全称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="企业性质" prop="companyType">
        <el-select
            v-model="queryParams.companyType"
            placeholder="请选择企业性质"
            clearable
            @change="handleQuery"
            style="width: 200px"
        >
          <el-option
              v-for="item in companyTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="企业规模" prop="companySize">
        <el-select
            v-model="queryParams.companySize"
            placeholder="请选择企业规模"
            clearable
            @change="handleQuery"
            style="width: 200px"
        >
          <el-option
              v-for="item in companySizeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:member:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table
        v-loading="loading"
        :data="memberList"
        @selection-change="handleSelectionChange"
        fit
        style="width: 100%"
        :show-header-overflow="true"
        :show-overflow-tooltip="true"
    >
      <el-table-column type="selection"  align="center" fixed="left" :resizable="false"/>
      <el-table-column label="操作" align="center"  fixed="left" class-name="small-padding fixed-width" :resizable="false" min-width="120">
        <template #default="scope" >
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['system:member:edit']">修改</el-button>
          <text> | </text>
          <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['system:member:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="企业logo" align="center" prop="companyLogo" min-width="120"/>
      <el-table-column label="企业全称" align="center" prop="companyName"  min-width="200"/>
      <el-table-column label="从事行业" align="center" prop="businessIndustry" min-width="120"/>
      <el-table-column label="企业性质" align="center" prop="companyType" min-width="120"/>
      <el-table-column label="企业规模" align="center" prop="companySize" min-width="120"/>
      <el-table-column label="所在地区" align="center" prop="region" min-width="150"/>
      <el-table-column label="详情地址" align="center" prop="address" min-width="150"/>
      <el-table-column label="企业简介" align="center" prop="companyProfile" min-width="120"/>
      <el-table-column label="企业联系电话" align="center" prop="companyPhone" min-width="150"/>
      <el-table-column label="联系人称呼" align="center" prop="contactName" min-width="120"/>
      <el-table-column label="联系人电话" align="center" prop="contactPhone" min-width="150"/>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改成员信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="memberRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="企业logo" prop="companyLogo">
          <el-input v-model="form.companyLogo" placeholder="请输入企业logo" />
        </el-form-item>
        <el-form-item label="企业全称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业全称" />
        </el-form-item>
        <el-form-item label="从事行业" prop="businessIndustry">
          <el-input v-model="form.businessIndustry" placeholder="请输入从事行业" />
        </el-form-item>
        <el-form-item label="企业性质" prop="companyType">
          <el-select v-model="form.companyType" placeholder="请选择企业性质" style="width: 100%">
            <el-option
                v-for="item in companyTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业规模" prop="companySize">
          <el-select v-model="form.companySize" placeholder="请选择企业规模" style="width: 100%">
            <el-option
                v-for="item in companySizeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-input v-model="form.region" placeholder="请输入所在地区" />
        </el-form-item>
        <el-form-item label="详情地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详情地址" />
        </el-form-item>
        <el-form-item label="企业简介" prop="companyProfile">
          <file-upload v-model="form.companyProfile"/>
        </el-form-item>
        <el-form-item label="企业联系电话" prop="companyPhone">
          <el-input v-model="form.companyPhone" placeholder="请输入企业联系电话" />
        </el-form-item>
        <el-form-item label="联系人称呼" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人称呼" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系人电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Member">
import { listMember, getMember, delMember, addMember, updateMember } from "@/api/system/member.js"
import { onMounted } from 'vue'

const { proxy } = getCurrentInstance()

const memberList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 企业性质选项
const companyTypeOptions = ref([])
// 企业规模选项
const companySizeOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyName: null,
    companyType: null,
    companySize: null,
  },
  rules: {
    companyName: [
      { required: true, message: "企业全称不能为空", trigger: "blur" }
    ],
    businessIndustry: [
      { required: true, message: "从事行业不能为空", trigger: "blur" }
    ],
    companyType: [
      { required: true, message: "企业性质不能为空", trigger: "change" }
    ],
    companySize: [
      { required: true, message: "企业规模不能为空", trigger: "change" }
    ],
    region: [
      { required: true, message: "所在地区不能为空", trigger: "blur" }
    ],
    address: [
      { required: true, message: "详情地址不能为空", trigger: "blur" }
    ],
    companyProfile: [
      { required: true, message: "企业简介不能为空", trigger: "blur" }
    ],
    companyPhone: [
      { required: true, message: "企业联系电话不能为空", trigger: "blur" }
    ],
    contactName: [
      { required: true, message: "联系人称呼不能为空", trigger: "blur" }
    ],
    contactPhone: [
      { required: true, message: "联系人电话不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询成员信息列表 */
function getList() {
  loading.value = true
  listMember(queryParams.value).then(response => {
    memberList.value = response.rows || []
    total.value = response.total || 0

    // 提取企业性质选项（去重）
    companyTypeOptions.value = extractUniqueOptions(response.rows, 'companyType')

    // 提取企业规模选项（去重）
    companySizeOptions.value = extractUniqueOptions(response.rows, 'companySize')

    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 通用方法：从数据中提取唯一选项
function extractUniqueOptions(data, field) {
  if (!Array.isArray(data)) return []

  return [...new Set(data
      .map(item => item[field])
      .filter(value => value != null && value !== '')
  )].map(value => ({
    value: value,
    label: value
  }))
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    companyLogo: null,
    companyName: null,
    businessIndustry: null,
    companyType: null,
    companySize: null,
    region: null,
    address: null,
    companyProfile: null,
    companyPhone: null,
    contactName: null,
    contactPhone: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("memberRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 确保下拉选项已加载
  if (companyTypeOptions.value.length === 0 || companySizeOptions.value.length === 0) {
    getList().then(() => {
      open.value = true
      title.value = "添加成员信息"
    })
  } else {
    open.value = true
    title.value = "添加成员信息"
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMember(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改成员信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["memberRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMember(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMember(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除成员信息编号为"' + _ids + '"的数据项？').then(function() {
    return delMember(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/member/export', {
    ...queryParams.value
  }, `member_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.dialog-footer {
  text-align: center;
  margin-top: 20px;
}
</style>